package com.tsinghuabigdata.edu.ddmath.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.fragment.BeansCourseFragment;
import com.tsinghuabigdata.edu.ddmath.fragment.BeansEvaluateFragment;
import com.tsinghuabigdata.edu.ddmath.fragment.IFragmentManage;
import com.tsinghuabigdata.edu.ddmath.fragment.IFragmentStackManage;
import com.tsinghuabigdata.edu.ddmath.fragment.MyCenterFragment;
import com.tsinghuabigdata.edu.ddmath.fragment.MyStudyFragment;
import com.tsinghuabigdata.edu.ddmath.fragment.StudyReportFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.view.BindMobileActivity;
import com.tsinghuabigdata.edu.ddmath.module.login.view.UsercenterFragment;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.SetHeadImage;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.WaitUploadActivity;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;
import com.tsinghuabigdata.edu.ddmath.util.DensityUtils;
import com.tsinghuabigdata.edu.ddmath.util.GlobalData;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;
import com.tsinghuabigdata.edu.ddmath.util.WindowUtils;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public class MainActivity extends RoboActivity implements View.OnClickListener, IFragmentManage, IFragmentStackManage {

    private static final String TAG = "MainActivity";

    public static final int FRAGMENT_MY_CENTER = 4;
    public static final int FRAGMENT_BEANS_COURSE = 0;
    private static final int FRAGMENT_BEANS_EVALUATE = 1;
    public static final int FRAGMENT_MY_COURSE = 2;
    private static final int FRAGMENT_STUDY_REPORT = 3;

    private int mCurPosition = FRAGMENT_BEANS_COURSE;

    //模拟activity的跳转方式管理fragment
    private Stack<Fragment> myCenterFS = new Stack<>();
    private Stack<Fragment> beansCourseFS = new Stack<>();
    private Stack<Fragment> beansEvaluateFS = new Stack<>();
    private Stack<Fragment> myCourseFS = new Stack<>();
    private Stack<Fragment> studyReportFS = new Stack<>();
    private List<Stack<Fragment>> fragmentStacks = new ArrayList<>();

    // 最底的几个fragment
    private BeansCourseFragment   mBeansCourseFragment;
    private BeansEvaluateFragment mBeansEvaluateFragment;
    private MyStudyFragment       mMyStudyFragment;
    private StudyReportFragment   mStudyReportFragment;
    private MyCenterFragment      mMyCenterFragment;
    private List<Fragment> mainFragments = new ArrayList<>();

    private LinearLayout mLlMain;
    private CircleImageView mIvHead;
    private LinearLayout mLlTeam;
    private LinearLayout mLlBeansCourse;
    private ImageView mIvBeansCourse;
    private TextView mTvBeansCourse;
    private LinearLayout mLlBeansEvaluate;
    private ImageView mIvBeansEvaluate;
    private TextView mTvBeansEvaluate;
    private LinearLayout mLlMyCourse;
    private ImageView mIvMyCourse;
    private TextView mTvMyCourse;
    private LinearLayout mLlStudyReport;
    private ImageView mIvStudyReport;
    private TextView mTvStudyReport;
    private FrameLayout mContainerFl;

    private long exitTime;
    private boolean queryClassSuccess = true;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFragment();
        initViews();
        initData();
        mContext = this;
        startAddImageReceiver();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        enterUsercenter();
        enterBindMobile();
    }

    private void initFragment() {
        mMyCenterFragment = new MyCenterFragment();
        mBeansCourseFragment = new BeansCourseFragment();
        mBeansEvaluateFragment = new BeansEvaluateFragment();
        mMyStudyFragment = new MyStudyFragment();
        mStudyReportFragment = new StudyReportFragment();

        mainFragments.add(mBeansCourseFragment);
        mainFragments.add(mBeansEvaluateFragment);
        mainFragments.add(mMyStudyFragment);
        mainFragments.add(mStudyReportFragment);
        mainFragments.add(mMyCenterFragment);

        //入栈管理
        beansCourseFS.push(mBeansCourseFragment);
        beansEvaluateFS.push(mBeansEvaluateFragment);
        myCourseFS.push(mMyStudyFragment);
        studyReportFS.push(mStudyReportFragment);
        myCenterFS.push(mMyCenterFragment);

        fragmentStacks.add(beansCourseFS);
        fragmentStacks.add(beansEvaluateFS);
        fragmentStacks.add(myCourseFS);
        fragmentStacks.add(studyReportFS);
        fragmentStacks.add(myCenterFS);
    }

    private void initViews() {
        mLlMain = (LinearLayout) findViewById(R.id.ll_main);
        mIvHead = (CircleImageView) findViewById(R.id.iv_head);
        mLlTeam = (LinearLayout) findViewById(R.id.ll_team);
        mLlBeansCourse = (LinearLayout) findViewById(R.id.ll_beans_course);
        mIvBeansCourse = (ImageView) findViewById(R.id.iv_beans_course);
        mTvBeansCourse = (TextView) findViewById(R.id.tv_beans_course);
        mLlBeansEvaluate = (LinearLayout) findViewById(R.id.ll_beans_evaluate);
        mIvBeansEvaluate = (ImageView) findViewById(R.id.iv_beans_evaluate);
        mTvBeansEvaluate = (TextView) findViewById(R.id.tv_beans_evaluate);
        mLlMyCourse = (LinearLayout) findViewById(R.id.ll_my_course);
        mIvMyCourse = (ImageView) findViewById(R.id.iv_my_course);
        mTvMyCourse = (TextView) findViewById(R.id.tv_my_course);
        mLlStudyReport = (LinearLayout) findViewById(R.id.ll_study_report);
        mIvStudyReport = (ImageView) findViewById(R.id.iv_study_report);
        mTvStudyReport = (TextView) findViewById(R.id.tv_study_report);
        mContainerFl = (FrameLayout) findViewById(R.id.container_fl);

        int screenHeight = WindowUtils.getScreenHeight(this);
        int statusBarHeight = WindowUtils.getStatusBarHeight(this);
        int bottomBarHeight = WindowUtils.getBottomBarHeight(this);
        int dis = DensityUtils.dp2px(this, 41 + 64 + 80 + 103 * 4 + 100);
        int remainHeight = screenHeight - statusBarHeight - bottomBarHeight - dis;
        Log.i(TAG, "screenHeight=" + screenHeight + "remainHeight=" + remainHeight);
        if (remainHeight < 0) {
            int margin = screenHeight - statusBarHeight - bottomBarHeight - DensityUtils.dp2px(this, 64 + 103 * 4);
            Log.i(TAG, "margin=" + margin);
            if (margin < 200) {
                LinearLayout.LayoutParams headParams = (LinearLayout.LayoutParams) mIvHead.getLayoutParams();
                int conHeight = screenHeight - statusBarHeight - bottomBarHeight;
                Log.i(TAG, "conHeight=" + conHeight);
                int all = 41 + 64 + 40 + (103 + 12) * 4 + 40;
                headParams.topMargin = conHeight * 41 / all;
                headParams.width = conHeight * 64 / all;
                headParams.height = conHeight * 64 / all;
                mIvHead.setLayoutParams(headParams);

                LinearLayout.LayoutParams teamParams = (LinearLayout.LayoutParams) mLlTeam.getLayoutParams();
                teamParams.topMargin = conHeight * 40 / all;
                teamParams.bottomMargin = conHeight * 40 / all;
                mLlTeam.setLayoutParams(teamParams);

                int ivHeight = conHeight * 76 / all;
                Log.i(TAG, "ivHeight=" + ivHeight);
                LinearLayout.LayoutParams params1 = (LinearLayout.LayoutParams) mIvBeansCourse.getLayoutParams();
                params1.width = ivHeight;
                params1.height = ivHeight;
                mIvBeansCourse.setLayoutParams(params1);
                LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams) mIvBeansEvaluate.getLayoutParams();
                params2.width = ivHeight;
                params2.height = ivHeight;
                mIvBeansEvaluate.setLayoutParams(params2);
                LinearLayout.LayoutParams params3 = (LinearLayout.LayoutParams) mIvMyCourse.getLayoutParams();
                params3.width = ivHeight;
                params3.height = ivHeight;
                mIvMyCourse.setLayoutParams(params3);
                LinearLayout.LayoutParams params4 = (LinearLayout.LayoutParams) mIvStudyReport.getLayoutParams();
                params4.width = ivHeight;
                params4.height = ivHeight;
                mIvStudyReport.setLayoutParams(params4);

            } else {
                LinearLayout.LayoutParams headParams = (LinearLayout.LayoutParams) mIvHead.getLayoutParams();
                headParams.topMargin = margin * 41 / (41 + 80 + 12 * 4 + 100);
                mIvHead.setLayoutParams(headParams);
                LinearLayout.LayoutParams teamParams = (LinearLayout.LayoutParams) mLlTeam.getLayoutParams();
                teamParams.topMargin = margin * 80 / (41 + 80 + 12 * 4 + 100);
                teamParams.bottomMargin = margin * 100 / (41 + 80 + 12 * 4 + 100);
                mLlTeam.setLayoutParams(teamParams);
            }
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container_fl, mMyCenterFragment).
                add(R.id.container_fl, mBeansCourseFragment).
                add(R.id.container_fl, mBeansEvaluateFragment).
                add(R.id.container_fl, mMyStudyFragment).
                add(R.id.container_fl, mStudyReportFragment)
                .hide(mMyCenterFragment).hide(mBeansEvaluateFragment).hide(mMyStudyFragment).hide(mStudyReportFragment)
                .commit();


        //默认豆豆课程
        mIvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(FRAGMENT_MY_CENTER);
            }
        });
        mIvHead.setOnClickListener(this);
        mIvBeansCourse.setActivated(true);
        mTvBeansCourse.setActivated(true);
        mTvBeansCourse.setTypeface(Typeface.DEFAULT_BOLD);
        mLlBeansCourse.setOnClickListener(this);
        mLlBeansEvaluate.setOnClickListener(this);
        mLlMyCourse.setOnClickListener(this);
        mLlStudyReport.setOnClickListener(this);
    }

    private void initData() {
        //登录判断
        if (AccountUtils.getLoginUser() != null && AccountUtils.getUserdetailInfo() != null) {
            //已登录
            UsercenterFragment usercenterFragment = new UsercenterFragment();
            myCenterFS.push(usercenterFragment);
            add(usercenterFragment);
        }

    }


    public boolean isLoginSuccess() {
        if (AccountUtils.getLoginUser() != null && AccountUtils.getUserdetailInfo() != null) {
            return true;
        } else {
            return false;
        }
    }

    private void enterUsercenter() {
        if (isLoginSuccess()) {
            boolean isshowUsercenter = PreferencesUtils.getBoolean(mContext, AppConst.IS_USERCENTER_SHOW, false);
            if (isshowUsercenter) {
                UsercenterFragment usercenterFragment = new UsercenterFragment();
                addStack(usercenterFragment, FRAGMENT_MY_CENTER);
                showTopfragment(FRAGMENT_MY_CENTER);
                PreferencesUtils.putBoolean(mContext, AppConst.IS_USERCENTER_SHOW, false);
            }
        }
    }

    private void enterBindMobile() {
        if (isLoginSuccess()) {
            if (TextUtils.isEmpty(AccountUtils.getUserdetailInfo().getPhone())) {
                goActivity(BindMobileActivity.class);
            }
        }
    }

    public void hideAllMainFragments() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        for (Fragment fragment : mainFragments) {
            fragmentTransaction.hide(fragment);
        }
        fragmentTransaction.commit();
    }

    public void showFragment(Fragment f) {
        hideAllMainFragments();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.show(f);
        fragmentTransaction.commit();
    }

    public void switchFragment(int position) {
        if (mCurPosition == position) {
            return;
        }
        for (int i = 0; i < mLlTeam.getChildCount(); i++) {
            LinearLayout child = (LinearLayout) mLlTeam.getChildAt(i);
            TextView textView = (TextView) child.getChildAt(1);
            if (position == i) {
                child.getChildAt(0).setActivated(true);
                textView.setActivated(true);
                textView.setTypeface(Typeface.DEFAULT_BOLD);
            } else {
                child.getChildAt(0).setActivated(false);
                textView.setActivated(false);
                textView.setTypeface(Typeface.DEFAULT);
            }
        }
        Fragment showedFragment = fragmentStacks.get(position).peek();
        showFragment(showedFragment);

        mCurPosition = position;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearFragments();

        stopAddImageReceiver();
    }

    private void clearFragments() {
        mainFragments.clear();
        for (Stack<Fragment> fs : fragmentStacks) {
            fs.clear();
        }
        fragmentStacks.clear();
    }

    @Override
    public void onClick(View v) {
        controllPolling(v.getId());
        switch (v.getId()) {
            case R.id.iv_head:
                switchFragment(FRAGMENT_MY_CENTER);
                break;
            case R.id.ll_beans_course:
                switchFragment(FRAGMENT_BEANS_COURSE);
                break;
            case R.id.ll_beans_evaluate:
                switchFragment(FRAGMENT_BEANS_EVALUATE);
                break;
            case R.id.ll_my_course:
                queryCourse();
                switchFragment(FRAGMENT_MY_COURSE);
                break;
            case R.id.ll_study_report:
                switchFragment(FRAGMENT_STUDY_REPORT);
                break;
        }
    }

    private void controllPolling(int id) {
        if (id==R.id.ll_my_course){
            mMyStudyFragment.controllPolling(true);
        }else {
            mMyStudyFragment.controllPolling(false);
        }
    }

    private void queryCourse() {
        boolean loginChange = GlobalData.isLoginChange();
        if (loginChange) {
            mMyStudyFragment.queryLoginInfo();
            GlobalData.setLoginChange(false);
        }
        if (!queryClassSuccess) {
            mMyStudyFragment.queryClass();
        }
    }

    public void setQueryClassSuccess(boolean queryClassSuccess) {
        this.queryClassSuccess = queryClassSuccess;
    }

    @Override
    public void add(Fragment f) {
        mainFragments.add(f);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.container_fl, f)
                .hide(f)
                .commit();
    }

    @Override
    public void remove(Fragment f) {
        if (mainFragments != null && mainFragments.size() > 0) {
            mainFragments.remove(f);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.remove(f).commit();
        }
    }

    @Override
    public void addStack(Fragment f, int stackIndex) {
        if (stackIndex >= fragmentStacks.size() || stackIndex < 0) {
            return;
        }

        Stack<Fragment> currentFragmentStack = fragmentStacks.get(stackIndex);
        fragmentStacks.get(stackIndex).push(f);
        add(f);
    }

    @Override
    public void removeFromStack(int stackIndex) {
        if (stackIndex >= fragmentStacks.size() || stackIndex < 0) {
            return;
        } else if (fragmentStacks.get(stackIndex).size() == 0) {
            return;
        }
        Fragment topFragment = fragmentStacks.get(stackIndex).pop();
        remove(topFragment);
        showTopfragment(stackIndex);
    }

    @Override
    public void showTopfragment(int stackIndex) {
        if (stackIndex >= fragmentStacks.size() || stackIndex < 0) {
            return;
        }
        Fragment topFragment = fragmentStacks.get(stackIndex).peek();
        showFragment(topFragment);
    }

    @Override
    public int getCurrentStackIndex() {
        return mCurPosition;
    }

    @Override
    public void onBackPressed() {
        //        super.onBackPressed();
        Stack<Fragment> currFS = fragmentStacks.get(mCurPosition);
        boolean b = isLoginSuccess() && currFS.size() == 2 && mCurPosition == FRAGMENT_MY_CENTER;
        if (currFS.size() > 1 && !b) {
            removeFromStack(mCurPosition);
        } else if ((System.currentTimeMillis() - exitTime) > 2000) {
            AlertManager.toast(this, "再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            //            finish();
            super.onBackPressed();
        }
    }


    public void setHead(UserDetailinfo userDetailinfo) {
        if (userDetailinfo == null) {
            mIvHead.setImageResource(R.drawable.personalcenter_bg_defaultface);
        } else {
            SetHeadImage.setHeadImage(this, mIvHead, userDetailinfo);
        }
    }

    //--------------------------------------------------------------------------------------------------------

    private StartActivityReceiver addImageReceiver;

    private void startAddImageReceiver() {
        addImageReceiver = new StartActivityReceiver();
        IntentFilter intentFilter = new IntentFilter(AppConst.ACTION_START_WAITUPLOAD);
        registerReceiver(addImageReceiver, intentFilter);
        //intentFilter = new IntentFilter( AppConst.ACTION_XBOOK_EDIT );
        //registerReceiver(addImageReceiver, intentFilter);
    }

    private void stopAddImageReceiver() {
        unregisterReceiver(addImageReceiver);
    }

    /**
     * 监听添加图片
     */
    class StartActivityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听消息
            if (AppConst.ACTION_START_WAITUPLOAD.equals(intent.getAction())) {
                //mWaitWorkAdapter.notifyDataSetChanged();
                startActivity(new Intent(mContext, WaitUploadActivity.class));

                AppLog.d("fdsfdsfdsfd main  startt");
            }
        }
    }
}
